import Vue from 'vue'
import VueRouter from 'vue-router'
import cookie from '@/utils/cookie'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/main',
    component: () => import('@/views/main'),
    children: [
      {
        path: '/home',
        component: () => import('@/views/home'),
        meta: {
          title: '首页'
        }
      },
      {
        path: '/classify',
        component: () => import('@/views/classify'),
        meta: {
          title: '分类'
        }
      },
      {
        path: '/car',
        component: () => import('@/views/car'),
        meta: {
          title: '购物车',
          isAuth: true
        }
      },
      {
        path: '/mine',
        component: () => import('@/views/mine'),
        meta: {
          title: '我的',
          isAuth: true
        }
      }
    ]
  },
  {
    path: '/login',
    component: () => import('@/views/login'),
    meta: {
      title: '登录'
    }
  },
  {
    path: '/icons',
    component: () => import('@/views/icon'),
    meta: {
      title: '图标'
    }
  },
  {
    path: '/search',
    component: () => import('@/views/search'),
    meta: {
      title: '搜索'
    }
  },
  {
    path: '/map/test',
    component: () => import('@/views/mapTest'),
    meta: {
      title: '地图测试'
    }
  },
  {
    path: '/geolocation',
    component: () => import('@/views/geolocation'),
    meta: {
      title: '定位'
    }
  },
  {
    path: '/select/location',
    component: () => import('@/views/selectLocation'),
    meta: {
      title: '选择位置'
    }
  },
  {
    path: '/edit/address',
    component: () => import('@/views/editAddress'),
    meta: {
      title: '添加地址',
      isAuth: true
    }
  },
  {
    path: '/map',
    component: () => import('@/views/map'),
    meta: {
      title: '选择位置',
      isAuth: true
    }
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  if (to.meta.isAuth) {
    const token = cookie.get('token')
    if (token) {
      next()
    } else {
      // 使用query传递非比传参数
      next({
        path: '/login',
        query: {
          callbackUrl: to.path
        }
      })
    }
  } else {
    next()
  }
})

router.afterEach((to, from) => {
  document.title = to.meta.title
})

export default router
